<?php

/**
 * Description of UserController
 * 
 * @author trongkhoi
 * @since Jun 28, 2013 - 10:00:41 AM
 */
class UserController extends MyController
{

    protected $type        = Users::TYPE_CUSTOMER;
    // Filter gan ukey cua biz dang duoc chon
    public $filterBusiness = 0;
    public $filterStaff    = 0;
    public $currentLimit   = 50;

    function init()
    {
        parent::init();

        $adminPage    = $this->type == Users::TYPE_ADMIN ? TRUE : FALSE;
        $bizPage      = $this->type == Users::TYPE_BUSINESS ? TRUE : FALSE;
        $staffPage    = $this->type == Users::TYPE_STAFF ? TRUE : FALSE;
        $customerPage = $this->type == Users::TYPE_CUSTOMER ? TRUE : FALSE;

        // Chỉ cho admin quản lý admin và bussiness user
        if ($adminPage or $bizPage)
        {
            if (!$this->isAdmin AND ! $this->isBussiness)
            {
                throw new CHttpException(403, Yii::t('yii', 'You are not authorized to perform this action.'));
            }
        }

        // Chỉ cho admin, bizUser và quản lý staff
        if ($staffPage)
        {
            if (!$this->isAdmin AND ! $this->isBussiness)
            {
                throw new CHttpException(403, Yii::t('yii', 'You are not authorized to perform this action.'));
            }
        }

        // Chỉ cho admin, bizUser, staff và quản lý customer
        if ($customerPage)
        {
            if (!$this->isAdmin AND ! $this->isBussiness AND ! $this->isStaff)
            {
                throw new CHttpException(403, Yii::t('yii', 'You are not authorized to perform this action.'));
            }
        }
    }

    protected function __criteria()
    {
        $criteria = new CDbCriteria();
        $key      = isset($_GET['key']) ? $_GET['key'] : '';
        if ($key)
        {
            $criteria->compare('lastname', $_GET['key'], TRUE, 'OR');
            $criteria->compare('firstname', $_GET['key'], TRUE, 'OR');
            $criteria->compare('country', $_GET['key'], TRUE, 'OR');
            $criteria->compare('address', $_GET['key'], TRUE, 'OR');
            $criteria->compare('home_phone', $_GET['key'], TRUE, 'OR');
            $criteria->compare('city', $_GET['key'], TRUE, 'OR');
            $criteria->compare('website', $_GET['key'], TRUE, 'OR');
            $criteria->compare('date_created', $_GET['key'], TRUE, 'OR');
            $criteria->compare('facebook', $_GET['key'], TRUE, 'OR');
            $criteria->compare('type', $_GET['key'], TRUE, 'OR');
            $criteria->compare('business_name', $_GET['key'], TRUE, 'OR');
            $criteria->compare('twitter', $_GET['key'], TRUE, 'OR');
            $criteria->compare('email', $_GET['key'], TRUE, 'OR');
        }
        return $criteria;
    }

    public function actionIndex()
    {
        $this->checkAccess();

        if ($this->isAdmin)
        {
            if (isset($_GET['business']))
            {
                $this->filterBusiness = $_GET['business'];
            }
            else
            {
                $bizArray = Users::getAllBussiness(TRUE);
                foreach ($bizArray as $bizId => $bizName)
                {
                    $this->filterBusiness = $bizId;
                    break;
                }
            }
        }

        if ($this->isBussiness)
        {
            $this->filterBusiness = Users::getUkeyById(Yii::app()->user->id);
        }

        if ($this->isAdmin OR $this->isBussiness)
        {
            if (isset($_GET['staff']))
            {
                $this->filterStaff = $_GET['staff'];
            }
            else
            {
                $staffArray = Users::getAllStaffByBusiness($this->filterBusiness, TRUE);
                foreach ($staffArray as $staffId => $staffName)
                {
                    $this->filterStaff = $staffId;
                    break;
                }
            }
        }

        $criteria = $this->__criteria();
        if ($this->type == Users::TYPE_STAFF && $this->filterBusiness)
        {
            $criteria->compare('author_id', Users::getIdByUkey($this->filterBusiness));
        }
        $criteria->compare('type', $this->type);

        $model            = Users::model();
        $count            = $model->count($criteria);
        $pages            = new CPagination($count);
        $pages->route     = $this->route;
        $pages->pageSize  = $this->currentLimit;
        $pages->applyLimit($criteria);
        $sort             = new CSort('Users');
        $sort->attributes = array(
            'business_name',
        );
        $sort->applyOrder($criteria);
        $data             = $model->findAll($criteria);

        $this->render('//user/index', array(
            'data'  => $data,
            'pages' => $pages,
            'sort'  => $sort,
            'type'  => $this->type,
        ));
    }

    public function actionDelete()
    {
        $this->checkAccess();

        // delete record
        if (isset($_GET['pk']))
        {
            $user = Users::model()->find('ukey=:u', array(':u' => $_GET['pk']));
            if ($user == NULL)
            {
                throw new CHttpException(404, 'User not found!');
            }

            if ($user->id == Users::SUPER_ADMIN)
            {
                throw new CHttpException(403, 'Root admin can not delete!');
            }

            $delete = $user->delete('ukey=:u', array(':u' => $_GET['pk']));
            if ($delete)
            {
                Yii::app()->user->setFlash('success', 'User deleted!');
            }
            else
            {
                Yii::app()->user->setFlash('error', 'Error, can not delete user, please try again!');
            }
        }
        $this->redirect($this->createUrl(strtolower($this->type) . '/index', @$_GET));
    }

    public function actionView($pk)
    {
        $this->checkAccess();
        $model = Users::model()->find("ukey=:u", array(':u' => $pk));
        if ($model == null)
            throw new CHttpException(404, Yii::t('yii', 'User not found!'));

        if (user()->isMerchant())
        {
            $list_branch_ids = Merchant::get_id_all_branch(user()->id, TRUE);
            if (!in_array($model->author_id, $list_branch_ids))
                throw new CHttpException(404, Yii::t('yii', 'User not found!'));
        }elseif (user()->isBranch())
            if ($model->author_id != user()->id)
                throw new CHttpException(404, Yii::t('yii', 'User not found!'));
        if ($model->type == Users::TYPE_STAFF)
        {
            $service_staff = ServiceStaff::model()->findAll("sukey=:u", array(':u' => $pk));
        }

        $this->render('//user/view', array(
            'user'          => $model,
            'service_staff' => @$service_staff
        ));
    }

    public function actionCreate()
    {
        $this->checkAccess();
        //Trường hợp Biz tạo mới Staff
        if ($this->isBussiness && $this->type == Users::TYPE_STAFF)
        {
            if (!$this->compareByPlan())
            {
                throw new CHttpException(400, 'Your plan has exceeded the number of staff. Please upgrade plan to create staff');
            }
        }
        $model = new Users();

        $model->type = $this->type;
        $model->setScenario("create_" . $model->type);
        $this->_form($model, 'create');
    }

    public function actionEdit($pk)
    {
        $this->checkAccess();

        $model = Users::model()->find("ukey=:u", array(':u' => $pk));
        if ($model == null)
            throw new CHttpException(404, Yii::t('yii', 'User not found!'));

        $model->setScenario("edit_" . $model->type);
        $this->_form($model, 'edit');
    }

    public function _form($model, $action)
    {
        $auth     = Yii::app()->authManager;
        $authItem = $auth->getAuthItem($model->type);

        if ($authItem == NULL)
            throw new CHttpException(404, Yii::t('yii', 'Invalid roles of user!'));

        if (Yii::app()->request->isAjaxRequest && $_POST['ajax'] == 'user-form')
        {
            $model->attributes = $_POST['Users'];
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['Users']))
        {
            $isNewRecord = $model->isNewRecord;

            /**
             * Upload ảnh mới và xóa ảnh cũ
             */
            $uploadPhoto = $this->_uploadPhoto('user');
            if ($uploadPhoto)
            {
                @unlink($model->photo);
                $model->photo = $uploadPhoto;
            }

            $model->date_created = time();
            $model->attributes   = $_POST['Users'];

            if (isset($_POST['Users']['birthday']))
            {
                if ($_POST['Users']['birthday'] != '')
                {
                    $birth_day       = ($_POST['Users']['birthday'] != '') ? str_replace('/', '-', $_POST['Users']['birthday']) : NULL;
                    $model->birthday = strtotime($birth_day);
                }
            }

            if (!isset($_POST['Users']['author_id']))
            {
                $model->author_id = Yii::app()->user->id;
            }

            if ($model->validate())
            {
                if ($this->save($model))
                {
                    if ($model->type == Users::TYPE_BUSINESS)
                    {
//                        Hotdeal::changeMerchantStatus($model->id, $model->status);
                        if (isset($_POST['Business']))
                        {
                            $model->business->attributes = $_POST['Business'];
                            if ($model->business->validate())
                            {
                                if ($model->isNewRecord)
                                {
                                    Yii::app()->user->setFlash(
                                            'success', "Created user $model->name successfully !"
                                    );
                                }
                                else
                                {
                                    Yii::app()->user->setFlash(
                                            'success', "Edit user $model->name successfully !"
                                    );
                                }
                                $auth = Yii::app()->authManager;

                                // Xóa các quyền đã gán trước đây đi
                                if ($auth->getAuthAssignments($model->id))
                                    foreach ($auth->getAuthAssignments($model->id) as $item)
                                        $auth->revoke($item->itemName, $model->id);

                                // Gán quyền mới 
                                $auth->assign($model->type, $model->id);

                                $this->redirect('index');
                            }
                            else
                            {
                                $err = CHtml::errorSummary($model->business);
                                Yii::app()->user->setFlash('error', $err);
                                $this->refresh();
                            }
                        }
                    }
                    else
                    {
                        if ($model->isNewRecord)
                        {
                            Yii::app()->user->setFlash(
                                    'success', "Created user $model->name successfully !"
                            );
                        }
                        else
                        {
                            Yii::app()->user->setFlash(
                                    'success', "Edit user $model->name successfully !"
                            );
                        }
                        $this->redirect('index');
                    }
                }
                else
                {
                    Yii::app()->user->setFlash('error', 'Can not save user, Please try again!');
                }
            }
            else
            {
                Yii::app()->user->setFlash('error', 'Please fill correct information !');
            }
        }
        $this->render('//user/form', array(
            'model'  => $model,
            'type'   => $model->type,
            'action' => $action
        ));
    }

    public function save($model)
    {
        $isNewRecord = $model->isNewRecord;
        $auth        = Yii::app()->authManager;
        if ($model->save())
        {
            // Sinh va lưu Ukey
            $model->updateUkey();

            // Đối với User mới
//            if ($isNewRecord)
//            {
            // Xóa các quyền đã gán trước đây đi
            if ($auth->getAuthAssignments($model->id))
                foreach ($auth->getAuthAssignments($model->id) as $item)
                    $auth->revoke($item->itemName, $model->id);

            // Gán quyền mới vào
            $auth->assign($model->type, $model->id);

            // Gửi mail cho user
            $newPwd = $_POST['Users']['new_pass'];
            $this->_sendMailToNewUser($model, $newPwd);
//            }
//            else
//            {
////                Yii::app()->user->setFlash(
////                    'success', "Edit user $model->name successfully !"
////                );
//            }

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * 
     * @param type $model
     * @param type $newPwd
     */
    protected function _sendMailToNewUser($model, $newPwd)
    {
        MyEmail::sendToNewUser($model, $newPwd);
    }

    /**
     * Check Create Staff number theo Plan của Merchant
     */
    protected function compareByPlan()
    {
        $plan = PlanMerchant::model()->find("merchant_id=" . Yii::app()->user->id);
        if ($plan)
        {
            $staff_number_exist = Users::model()->count("author_id=" . Yii::app()->user->id);
            if ($plan->plan->staff_number > 0)//Có giới hạn, ngược lại là loại Plan Unlimited staff number
            {
                if ($staff_number_exist >= $plan->plan->staff_number)
                {
                    return FALSE;
                }
            }
        }
        return TRUE;
    }

}

/**
 * End of UserController
 */